#include "distancemeasure.h"
#include "spatial3danalysis/analysis3dmeasurelength.h"
#include "globecontrol/globecontrol.h"
#include "measurelistener.h"

using namespace EarthView::World::Spatial3D::Controls;
using namespace EarthView::World::Spatial3D::Analysis;

DistanceMeasure::DistanceMeasure(QWidget *parent, Qt::WFlags flags)
	: QWidget(parent, flags)
{
	ui.setupUi(this);
	connect(ui.btnClear,SIGNAL(clicked()),SLOT(slotClear()));
	connect(ui.btnExit,SIGNAL(clicked()),SLOT(slotExit()));
	mpLengthTool = NULL;
	mpGlobeControl = NULL;
	mpMeasureListener = NULL;
	this->setFixedSize(400,220);
}

void DistanceMeasure::closeEvent(QCloseEvent *)
{
	slotClear();
	mpGlobeControl->setCurrentTool(NULL);
}

void DistanceMeasure::setGlobeControl(CGlobeControl* ref_globeControl)
{
	mpGlobeControl = ref_globeControl;
	if(!mpMeasureListener)
	{
		mpMeasureListener = new CMeasureListener();
		mpMeasureListener->setWidget(this);
	}
	if(!mpLengthTool)
	{
		mpLengthTool = new CAnalysis3DMeasureLength(ref_globeControl);
		mpLengthTool->setSearchInterval(1000000);
		mpLengthTool->setUseHighestDem(false);
		mpLengthTool->setAnalysis3DListener(mpMeasureListener);
	}
	ref_globeControl->setCurrentTool(mpLengthTool);

}

DistanceMeasure::~DistanceMeasure()
{
	if (mpGlobeControl)
	{
		mpGlobeControl->setCurrentTool(NULL);
	}
	
	if (mpLengthTool)
	{
		delete mpLengthTool;
		mpLengthTool = NULL;
	}
	
	delete mpMeasureListener;
}

void DistanceMeasure::slotClear()
{
	if (mpGlobeControl->getCurrentTool()==mpLengthTool)
	{
		ui.leClampDis->setText("");
		ui.leStraightDis->setText("");
		mpMeasureListener->clearDis();
		mpGlobeControl->setCurrentTool(NULL);
		delete mpLengthTool;
		mpLengthTool= NULL;

		mpLengthTool = new CAnalysis3DMeasureLength(mpGlobeControl);
		mpLengthTool->setSearchInterval(1000000);
		mpLengthTool->setUseHighestDem(false);
		mpLengthTool->setAnalysis3DListener(mpMeasureListener);
	    mpGlobeControl->setCurrentTool(mpLengthTool);
	}
}

void DistanceMeasure::slotExit()
{
	ui.leClampDis->setText("");
	ui.leStraightDis->setText("");
	mpMeasureListener->clearDis();
	mpGlobeControl->setCurrentTool(NULL);
	delete mpLengthTool;
	mpLengthTool= NULL;
	this->close();
}

void DistanceMeasure::setText(const QString& clamTxt, const QString& straTxt)
{
	ui.leClampDis->setText(clamTxt);
	ui.leStraightDis->setText(straTxt);
}
